"use strict";

module.exports = { getNpmInfo, getDefaultRegistry };

const axios = require("axios").default;
const urlJoin = require("url-join");

function getNpmInfo(npmName, registry) {
  if (!npmName) return null;
  const npmInfoURL = urlJoin(registry || getDefaultRegistry(), npmName);
  if (npmInfoURL) {
    return axios
      .get(npmInfoURL)
      .then((response) => {
        if (response.status === 200) {
          const data = response.data;
          return {
            extra: data,
            versions: getVersions(data),
            lastVersion: getLastVersion(data),
          };
        }
        return null;
      })
      .catch((err) => {
        // console.error(err);
        console.error(`getNpmInfo (${npmName}) error:`, err);
      });
  }
  return null;
}

function getVersions(data) {
  if (!data) return null;
  return Object.keys(data.versions);
}

function getLastVersion(data) {
  if (!data) return null;
  return data["dist-tags"].latest;
}

function getDefaultRegistry() {
  return "https://registry.npmjs.com/";
}
